package com.nisure.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.drapi.autosdk.exception.ApiException;
import com.nisure.AutoKeywordApplication;
import com.nisure.common.CommonData;
import com.nisure.common.CreateJsonObject;
import com.nisure.common.GetHttpJsonobject;
import com.nisure.common.R;
import com.nisure.entity.CampaignEntity;
import com.nisure.info.CampaignTypeInfo;
import com.nisure.service.CampaignService;
import com.nisure.type.CampaignType;

@RestController
public class CampaignController {

	private static final Logger logger = LoggerFactory
			.getLogger(AutoKeywordApplication.class);

	@Autowired
	private GetHttpJsonobject getHttpJsonobject;
	@Autowired
	private CampaignService campaignService;
	@Autowired
	private AccountController accountController;
	@Autowired
	private CreateJsonObject createJsonObject;

	public String addCampaign(String accessToken, String campaignName) {

		// 获得推广账户的所有推广计划
		String url = "https://api.baidu.com/json/sms/v4/CampaignService/addCampaign";
		JSONObject campaignjson = this.getCampaign(accessToken, null);
		campaignjson = JSONObject.parseObject(campaignjson.getString("body"));
		JSONArray campaignarr = JSONArray.parseArray(campaignjson
				.getString("data"));
		String campaignId = null;
		if (campaignarr.size() > 0) {
			for (int i = 0; i < campaignarr.size(); i++) {
				JSONObject jsonobj = campaignarr.getJSONObject(i);
				if (jsonobj.getString("campaignName").equals(campaignName)) {// 存在
					campaignId = jsonobj.getString("campaignId");
				}
			}
		}
		if (campaignId == null) {// 不存在，添加
			JSONObject paramsList = new JSONObject();
			paramsList.put("campaignName", campaignName);
			paramsList.put("pause", true);

			List<JSONObject> jsonList = new ArrayList<JSONObject>();
			jsonList.add(paramsList);
			JSONObject jsonParams = new JSONObject();
			jsonParams.put("campaignTypes", jsonList);

			JSONObject completeJson = createJsonObject.getJsonData(accessToken,
					jsonParams);
			JSONObject jsonobj = getHttpJsonobject.httpsRequest(url, "POST",
					completeJson.toJSONString());
			jsonobj = JSONObject.parseObject(jsonobj.getString("body"));
			JSONArray responseArr = JSONArray.parseArray(jsonobj
					.getString("data"));
			JSONObject responseData = responseArr.getJSONObject(0);
			campaignId = responseData.getString("campaignId");
		}
		return campaignId;

	}

	public JSONObject getCampaign(String accessToken, String[] ids) {

		String url = "https://api.baidu.com/json/sms/v4/CampaignService/getCampaign";
		String fields = "campaignName,budget,regionTarget,negativeWords,exactNegativeWords,schedule,budgetOfflineTime,"
				+ "showProb,pause,status,isDynamicCreative,campaignType,device,priceRatio";
		String[] str = fields.split(",");
		List<String> list = Arrays.asList(str);

		JSONObject jsonParams = new JSONObject();

		if (ids == null) {
			jsonParams.put("campaignIds", null);
		} else {
			List<String> idList = new ArrayList<String>();
			for (String id : ids) {
				idList.add(id);
			}
			jsonParams.put("campaignIds", idList);

		}
		jsonParams.put("campaignFields", list);
		jsonParams.put("mobileExtend", 1);
		JSONObject completeJson = createJsonObject.getJsonData(accessToken,
				jsonParams);
		JSONObject campaignjson = getHttpJsonobject.httpsRequest(url, "POST",
				JSONObject.toJSONString(completeJson,
						SerializerFeature.WriteMapNullValue));// SerializerFeature.WriteMapNullValue是允许传null值
		return campaignjson;

	}

	public List<Long> saveAllCampaign(String accessToken, long userId) {

		JSONObject campaignjson = this.getCampaign(accessToken, null);
		JSONObject bodyjson = JSONObject.parseObject(campaignjson
				.getString("body"));
		if (campaignjson.getString("body") == null) {
			logger.info(campaignjson.toJSONString());
			return null;
		}
		if (JSONObject.parseArray(bodyjson.getString("data")).isEmpty()) {
			logger.info(userId + "计划为空");
			return null;
		}
		JSONArray array = JSONObject.parseArray(bodyjson.getString("data"));
		List<CampaignType> campaignTypeList = JSON.parseArray(
				array.toJSONString(), CampaignType.class);
		List<CampaignTypeInfo> campaignTypeInfoList = new ArrayList<CampaignTypeInfo>();
		List<Long> campaignIdList = new ArrayList<Long>();

		for (CampaignType c : campaignTypeList) {
			campaignIdList.add(c.getCampaignId());
			CampaignTypeInfo campaignTypeInfo = new CampaignTypeInfo();
			BeanUtils.copyProperties(c, campaignTypeInfo);
			campaignTypeInfo.setPause(c.isPause() + "");// 数据库不能存布尔类型
			campaignTypeInfo.setIsDynamicCreative(c.isDynamicCreative() + "");// 数据库不能存布尔类型
			campaignTypeInfo.setUserId(userId);
			campaignTypeInfoList.add(campaignTypeInfo);
		}

		int result = campaignService.saveAllCampaign(campaignTypeInfoList);
		if (result > 0) {
			// 返回所有id
			return campaignIdList;
		}
		return null;

	}
	
}
